<?php


namespace Xtsb\Cims\Ocr\Custom;


use DateTime;

class Train
{
  static function data(){
    return '
        algo_version": "5d7591fa64b2e4a91d08b0743c22147c34558db2",
        "angle": 0,
        "data": {
          "出发站": "合肥南站",
          "出发站拼音": "Hefcinan",
          "到达站": "厦门北站",
          "到达站拼音": "Xiamenori",
          "售票码": "19423300371028Q045573",
          "售票车站信息": "JM",
          "座位号": "06+12A号",
          "座位类型": "二等座",
          "开车时间": "2023*10月27日09:24开",
          "旅客信息": "3504261984****2013李忠杰",
          "旅客姓名": "李忠杰",
          "检票口": "17B",
          "票价": "478.0",
          "票号": "Z37Q045573",
          "车次": "G1601"
        }
    ';
  }
  
  static function structure($data){
    return [
      'supplier_name'=>null,
      'seller_info'=>[
        'name'=>null,
        'bank'=>'',
        'address'=>'',
        'tax_no'=>null,
        'tax_rate'=>null,
      ],
      'amount_all'=>$data['票价']??"",
      'not_tax_money_all'=>0,
      'tax_money_all'=>0,
      'invoice_date'=>self::dateMatch($data['开车时间']??""),

      'purchase_name'=>$data['旅客姓名']??null,
      'purchase_info'=>[
        'name'=>$data['旅客姓名']??null,
        'bank'=>'',
        'address'=>'',
        'tax_no'=>null,
      ],

      'invoice_order_no'=>$data['售票码']??null,
      'code'=>$data['票号']??null,
      'invoice_type'=>1,
      'invoice_org'=>null,
      'machine_code'=>null,
      'check_code'=>null,
      'invoice_list' =>[
        [
          'row_num'=>1,
          'content'=>($data['出发站']??"").'到'.($data['到达站']??""),
          'sku'=>'',
          'unit'=>'',
          'num'=>1,
          'price'=>$data['票价'],
          'amount'=>$data['票价'],
          'tax_rate'=>null,
          'tax_money'=>null,
          'not_tax_money'=>null
        ]
      ]
    ];
  }


  static function dateMatch($string){
    if(!$string){
      return null;
    }
    $pattern = '/(\d{4}).*?(\d{1,2}).*?(\d{1,2}).*?(\d{2}):(\d{2})/';

    $result = null; // 未找到匹配项
    if (preg_match($pattern, $string, $matches)) {
      // 提取匹配的部分
      $year = $matches[1];
      $month = $matches[2];
      $day = $matches[3];
      $hour = $matches[4];
      $minute = $matches[5];

      // 构建日期时间字符串并进行转换
      $formattedDateTime = sprintf("%04d-%02d-%02d %02d:%02d", $year, $month, $day, $hour, $minute);

      // 使用 DateTime 类来验证日期时间并输出格式化的日期时间
      $dateTime = DateTime::createFromFormat('Y-m-d H:i', $formattedDateTime);
      $result = null; // 无法解析的日期时间
      if ($dateTime !== false) {
        $result = $dateTime->format('Y-m-d H:i');
      }
    }
    return $result;
  }
}